# -*- coding: utf-8 -*-
"""
@File: insert_test_data.py
@author: chenxialin
@time: 4月 08, 2025 10:43
"""
import random
from datetime import timedelta
from django.core.management.base import BaseCommand
from django.utils.timezone import now
from django.contrib.auth.models import User as AuthUser
from book.models import Announcement, Book, UserProfile, BorrowRecord, Rating

class Command(BaseCommand):
    help = "Insert test data into the database and truncate existing data"

    def handle(self, *args, **options):
        # 清空所有表的数据
        self.truncate_tables()

        # 插入测试数据
        self.insert_users()
        self.insert_announcements()
        self.insert_books()
        self.insert_user_profiles()
        self.insert_borrow_records()
        self.insert_ratings()

        self.stdout.write(self.style.SUCCESS("成功插入所有测试数据！"))

    def truncate_tables(self):
        """
        清空所有表的数据
        """
        models = [Announcement, Book, UserProfile, BorrowRecord, Rating, AuthUser]
        for model in models:
            model.objects.all().delete()
        self.stdout.write(self.style.WARNING("已清空所有表的数据"))

    def insert_users(self):
        """
        插入用户数据
        """
        users = []
        for i in range(1, 11):
            username = f"user{i}"
            email = f"user{i}@example.com"
            password = "password123"
            user, created = AuthUser.objects.get_or_create(username=username, email=email)
            if created:
                user.set_password(password)
                user.save()
            users.append(user)
        self.stdout.write(self.style.SUCCESS(f"成功插入 {len(users)} 条用户数据"))

    def insert_announcements(self):
        """
        插入公告数据
        """
        announcements = [
            {"title": "图书馆闭馆通知", "content": "因系统升级，图书馆将于本周五闭馆一天。"},
            {"title": "新书推荐活动", "content": "本周六将举行新书推荐活动，欢迎参加。"},
            {"title": "系统维护公告", "content": "系统将于今晚进行维护，请提前保存您的工作。"},
            {"title": "暑期开放时间调整", "content": "暑假期间开放时间调整为上午9点至下午5点。"},
            {"title": "图书借阅规则更新", "content": "新的借阅规则已生效，请查阅详情。"},
            {"title": "读书分享会邀请", "content": "本周日将举办读书分享会，主题为科幻小说。"},
            {"title": "电子资源使用指南", "content": "如何使用图书馆的电子资源？点击查看指南。"},
            {"title": "周末特别活动", "content": "本周末有特别活动，详情请关注公告。"},
            {"title": "图书馆搬迁通知", "content": "图书馆将于下月搬迁至新址，敬请留意。"},
            {"title": "春季阅读挑战赛", "content": "参加春季阅读挑战赛，赢取精美礼品！"},
        ]
        for data in announcements:
            Announcement.objects.create(
                title=data["title"],
                content=data["content"],
                is_visible=random.choice([True, False]),
                published_at=now() - timedelta(days=random.randint(0, 30)),
            )
        self.stdout.write(self.style.SUCCESS(f"成功插入 {len(announcements)} 条公告数据"))

    def insert_books(self):
        """
        插入书籍数据
        """
        books = [
            {"title": "Python编程：从入门到实践", "author": "Eric Matthes", "category": "编程", "isbn": "9787115428028"},
            {"title": "深入理解计算机系统", "author": "Randal E. Bryant", "category": "计算机科学", "isbn": "9787111407010"},
            {"title": "算法导论", "author": "Thomas H. Cormen", "category": "算法", "isbn": "9787111407027"},
            {"title": "机器学习", "author": "周志华", "category": "人工智能", "isbn": "9787302426544"},
            {"title": "深度学习", "author": "Ian Goodfellow", "category": "人工智能", "isbn": "9787111592528"},
            {"title": "人性的弱点", "author": "Dale Carnegie", "category": "心理学", "isbn": "9787506385266"},
            {"title": "小王子", "author": "Antoine de Saint-Exupéry", "category": "文学", "isbn": "9787544261085"},
            {"title": "白鹿原上的春夏秋冬", "author": "陈忠实", "category": "文学", "isbn": "9787020089536"},
            {"title": "人类简史", "author": "Yuval Noah Harari", "category": "历史", "isbn": "9787508660752"},
            {"title": "经济学原理", "author": "Gregory Mankiw", "category": "经济", "isbn": "9787302466582"},
        ]
        for data in books:
            Book.objects.create(
                title=data["title"],
                author=data["author"],
                category=data["category"],
                publish_date=now().date() - timedelta(days=random.randint(0, 365 * 5)),
                isbn=data["isbn"],
                description=f"这是一本关于{data['category']}的好书。",
            )
        self.stdout.write(self.style.SUCCESS(f"成功插入 {len(books)} 条书籍数据"))

    def insert_user_profiles(self):
        """
        插入用户档案数据
        """
        for user in AuthUser.objects.all():
            UserProfile.objects.get_or_create(user=user)
        self.stdout.write(self.style.SUCCESS(f"成功插入 {AuthUser.objects.count()} 条用户档案数据"))

    def insert_borrow_records(self):
        """
        插入借阅记录数据
        """
        books_all = list(Book.objects.all())
        users = list(AuthUser.objects.all())
        for user in users:
            for _ in range(random.randint(1, 5)):  # 每个用户随机借阅1到5本书
                book = random.choice(books_all)
                borrow_date = now() - timedelta(days=random.randint(0, 30))
                return_date = borrow_date + timedelta(days=random.randint(7, 30)) if random.random() > 0.5 else None
                BorrowRecord.objects.create(
                    user=user,
                    book=book,
                    borrow_date=borrow_date,
                    return_date=return_date,
                )
        self.stdout.write(self.style.SUCCESS(f"成功插入 {BorrowRecord.objects.count()} 条借阅记录数据"))

    def insert_ratings(self):
        """
        插入评分数据
        """
        books_all = list(Book.objects.all())
        users = list(AuthUser.objects.all())
        for user in users:
            for book in random.sample(books_all, k=random.randint(1, 5)):  # 每个用户随机对1到5本书评分
                score = random.randint(1, 5)
                Rating.objects.get_or_create(
                    user=user,
                    book=book,
                    score=score,
                )
        self.stdout.write(self.style.SUCCESS(f"成功插入 {Rating.objects.count()} 条评分数据"))